package com.hp.bon.sgw.wh.channel.handler;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.hp.bon.sgw.Constants;
import com.hp.bon.sgw.bean.XmlMessage;
import com.hp.bon.sgw.core.BuzProcessorManager;
import com.hp.bon.sgw.core.CallParam;
import com.hp.bon.sgw.core.channel.SoapChannel;
import com.hp.bon.sgw.core.channel.handler.IAsynCallHandler;
import com.hp.bon.sgw.threads.TaskManager;
import com.hp.bon.sgw.wh.service.UserResourceConfigService;
import com.hp.bon.sgw.wh.utils.LogUtil;
import com.hp.bon.sgw.wh.utils.ResultCodeUtil;
import com.hp.ocs.diameter.DiameterUtils;
import com.hp.ocs.diameter.message.*;
import org.apache.commons.lang.StringUtils;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.simpleframework.http.Request;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: YEBDHZCXHandle
 * @Description: 余额变动汇总查询查询
 * @author: zhoumengyi
 * @date:2019年6月26日 上午11:59:30
 */
public class YEBDHZCXHandle implements IAsynCallHandler {
	private static final Logger _log = LoggerFactory.getLogger(YEBDHZCXHandle.class);

	private PrintStream printStream;
	private String balanceTypeFlag;
	private JSONObject jsonContent;
    private long startTime;
    private Request request;
	private UserResourceConfigService userResourceConfigService ;
	public YEBDHZCXHandle(PrintStream printStream, String balanceTypeFlag, JSONObject jsonContent, Request request, long startTime) {
		this.printStream = printStream;
		this.balanceTypeFlag = balanceTypeFlag;
		this.jsonContent = jsonContent;
        this.startTime = startTime;
        this.request = request;
	}

	@Override
	public int getProtocolType() {
		return 0;
	}

	@Override
	public void onCallResult(CallParam callParam) {
		XmlMessage ack = null;
		Object response = null;
		if (callParam.getResponse() != null) {
			response = callParam.getResponse();
		} else if (callParam.getRecvResponse() != null) {
			response = callParam.getRecvResponse();
		}
		if (response == null) {
			int _retcodeTmp = callParam.getRetCode() == 3002 ? 11202 : callParam.getRetCode();
			ack = SoapChannel.createERRAnwser(callParam.getSessionId(), _retcodeTmp, callParam.getResultMsg());
			callParam.setServiceResultCode(_retcodeTmp);// 11203
		} else {
			if (response instanceof Message) {// CCA -> XML
                _log.info("================response instanceof Message");
                ack = BuzProcessorManager.getInstance().convertMessageToAck(callParam);
			} else if (response instanceof XmlMessage) {
                _log.info("================response instanceof XmlMessage");
                ack = (XmlMessage) response;
			} else {
				_log.warn("unknown response type:" + callParam.getResponse().getClass().getName());
			}
		}
		try {
			String respXML = convertResponseString((Message) response, callParam.getServiceResultCode());
			if("0".equals(respXML)) {
				return;
			}

			byte[] resp = respXML.getBytes("UTF-8");
			ack.setLength(resp.length);
			ack.setMsgTime(System.currentTimeMillis());
			printStream.write(resp);
			printStream.close();
			callParam.setResponse(ack);
//			if (callParam.getRetCode() == Constants.ResultCode.SUCCESS) {// 成功的消息，请求应答入库
//				MessageDetail detail = new MessageDetail();
//				detail.setBusinessCallId(callParam.getBussinessCallId());
//				detail.setSessionId(callParam.getSessionId());
//				detail.setServiceContextId(callParam.getServiceContextId());
//				detail.setMessageType(MessageType.WSA);
//				detail.setDetails(ack.getDATA());
//				detail.setMsgTime(new Date(ack.getMsgTime()));
//				detail.setOpType("send");
//				detail.setHostId(callParam.getUserName());
//				MessageDetailCacheManager.getInstance().add(detail);
//			}
            //记录到日志
            LogUtil.saveLogToABM(request,respXML,startTime);
			TaskManager.taskProcess(callParam);
            _log.info("http response(cfq) " + respXML);

		} catch (UnsupportedEncodingException e) {
			_log.info("convertResponseString UnsupportedEncodingException error,msg=" + e.getMessage());
		} catch (IOException e) {
			_log.info("convertResponseString IOException,msg=" + e.getMessage());
		}
	}

	
	/**
	 * 从Message中解析出需要的数据，并拼接成json字符串
	 * @param answer
	 * @param serviceResultCode
	 * @return
	 */
	@SuppressWarnings("all")
	private String convertResponseString(Message answer, int serviceResultCode) {
		_log.info("HBCFQHandle serviceResultCode = {}", serviceResultCode);
        _log.info("===========service_result_code===============" + serviceResultCode);
        String response = "";
		Map<String, Object> data = new HashMap<String, Object>();
		Map<String, Object> map = getAvpsFromMessage(answer);
		Gson gson = new Gson();
		if (null == map) {
			data.put("resultCode", "-1");
			data.put("resultMsg", "查询失败");
		}else if(serviceResultCode != 0){
            data.put("resultCode", serviceResultCode+"");
            data.put("resultMsg", "查询失败");
		}else{
			String jf3_flag=userResourceConfigService.getValue("jf3_flag", "0");
			if("1".equals(jf3_flag)) {
                _log.info("==============新流程解析=========================");
				//新的接口解析
				String Latn_Id = null;
				String Area_Code = null;
			    AVP avp = answer.find(Constants.DIAMETER_AVP_SERVICE_INFOMATION,Constants.DIAMETER_VENDOR_3GPP);
			    AVP_Grouped avpServiceInfomation;
				try {
					avpServiceInfomation = new AVP_Grouped(avp);
				    AVP avpBillSerialNbr = avpServiceInfomation.find(80411,Constants.DIAMETER_VENDOR_CT);
				    if (avpBillSerialNbr != null){
				    	Latn_Id = new AVP_UTF8String(avpBillSerialNbr).queryValue();
				    }
				    AVP avpBillSerialNbr2 = avpServiceInfomation.find(50207,Constants.DIAMETER_VENDOR_CT);
				    if (avpBillSerialNbr2 != null){
				    	Area_Code = new AVP_UTF8String(avpBillSerialNbr2).queryValue();
				    }
					
				} catch (InvalidAVPLengthException e) {
					_log.error(" get  Latn_Id  getAvpsFromMessage is error when Ne response cca message");
				}
				String versionType = getVersionType(Latn_Id, "0");//传参0 1001类 传1 84210类   返参 1 新 0 旧的
				String objType = jsonContent.getJSONObject("svcObjectStruct").getString("objType");
				String objValue = jsonContent.getJSONObject("svcObjectStruct").getString("objValue");
				String objAttr = jsonContent.getJSONObject("svcObjectStruct").getString("objAttr");
				String dataArea = jsonContent.getJSONObject("svcObjectStruct").getString("dataArea");
				Element serviceInformation = null;
				if("1".equals(versionType)) {
                    _log.info("==============新流程中的新流程入参=========================");
					//开关开,调用新流程
					serviceInformation = DocumentHelper.createElement("Service_Information");
					serviceInformation.addElement("Channel_Id").setText("200");
					serviceInformation.addElement("Area_Code").setText(Area_Code);
					serviceInformation.addElement("DestinationAttr").setText(objAttr);
					serviceInformation.addElement("Destination_Id").setText(objValue);
					serviceInformation.addElement("Destination_Id_Type").setText("2");
					serviceInformation.addElement("Billing_Cycle").setText(jsonContent.getString("billingCycleId"));
					_log.info("Area_Code:"+Area_Code+"  objAttr:"+objAttr+"  objValue:"+objValue+"  billingCycleId:"+jsonContent.getString("billingCycleId"));
				}else {
                    _log.info("==============新流程中的旧流程入参=========================");
					//开关 关,旧流程
					serviceInformation = DocumentHelper.createElement("Service_Information");
					Element element = serviceInformation.addElement("Acc_Nbr");
					element.setText((jsonContent.getJSONObject("svcObjectStruct")).get("objValue") + "");
					element = serviceInformation.addElement("DestinationAttr");// 用户属性 0固话、1小灵通、2移动、3宽带、4智能公话、5互联星空、6天翼高清、99未知
					element.setText((jsonContent.getJSONObject("svcObjectStruct")).get("objAttr") + "");
					element = serviceInformation.addElement("Billing_Cycle");
					element.setText(jsonContent.get("billingCycleId") + "");
					element = serviceInformation.addElement("QueryType");
					element.setText("0");
				}
                _log.info("==============旧流程=========================");
				XmlMessage req = new XmlMessage(true);
				String tmallHostId = "SGWHBCFQ@027.ctnbc-bon.net";
				String sessionId = DiameterUtils.makeSessionID(tmallHostId);
				req.setIp(jsonContent.getString("IP"));
				req.setMsgTime(System.currentTimeMillis());
				req.setMID(sessionId);
				req.setUID(tmallHostId);
				req.setSCID("1".equals(versionType) ? "BalanceRecord.jf3@027.ctnbc-bon.net" : "BalanceRecord.balanceYXHB9@027.ctnbc-bon.net");
				req.setSIG(null);
				req.setREPTAG(0);
				req.setDATA(serviceInformation.asXML());
				req.setDataElement(serviceInformation);
				// new CallParam对象
				YEBDHZCXHandle2 returnBalanceHandle = new YEBDHZCXHandle2(printStream,jsonContent.getString("balanceTypeFlag"),jsonContent,request,startTime);
				CallParam callParam = new CallParam(req.getMID(), req.getSCID(), req, req.getUID(), returnBalanceHandle);
				BuzProcessorManager.getInstance().processRequest(callParam);
				
				return "0";
			}
            _log.info("==============旧流程数据解析=========================");
			data.put("resultCode", "0");
			data.put("resultMsg", "SUCCESS");
            data.put("billingCycleId",jsonContent.getLongValue("billingCycleId"));
			List<Map<String, Object>> list  = (List<Map<String, Object>>)map.get("BalanceRecordInfo");
			List<Map<String, Object>> newList =new ArrayList<Map<String,Object>>();
			if(list != null && StringUtils.isNotBlank(balanceTypeFlag)){
				for(Map<String, Object> one : list){
					if(StringUtils.isNotBlank(balanceTypeFlag) &&balanceTypeFlag.equals(one.get("balanceTypeFlag"))){
						newList.add(one);
					}
				}
				data.put("balanceTypeFlagQuery", newList);
			}else if(list != null && StringUtils.isBlank(balanceTypeFlag)) {
				data.put("balanceTypeFlagQuery", list);
			}else {
				data.put("balanceTypeFlagQuery", newList);
			}
			
		}
        String newCode = ResultCodeUtil.updateResultCode(data.get("resultCode"), userResourceConfigService.getValue("api_resultCode"), userResourceConfigService.getValue("api_defaultResult"));
        data.put("resultCode", newCode);
		response = gson.toJson(data);
		return response;
	}

	
	/**
	 * 处理CCA结果
	 * @param answer
	 * @return 解析信息出现异常返回null
	 */
	public Map<String, Object> getAvpsFromMessage(Message answer) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		try {
			AVP avp = answer.find(Constants.DIAMETER_AVP_SERVICE_INFOMATION, Constants.DIAMETER_VENDOR_3GPP);
			AVP_Grouped avpServiceInfomation = new AVP_Grouped(avp);
			AVP[] avps = avpServiceInfomation.queryAVPs();
			for (AVP avpData : avps) {
				if(avpData.code() == 20631 && avpData.vendorID() == 81000){
					// Result节点
					map.put("Result", String.valueOf(new AVP_Unsigned32(avpData).queryValue()));
				}else if(avpData.code() == 80407 && avpData.vendorID() == 81000){
					// Para_Field_Result节点
					map.put("Para_Field_Result", String.valueOf(new AVP_UTF8String(avpData).queryValue()));
				}else if (avpData.code() == 90220 && avpData.vendorID() == Constants.DIAMETER_VENDOR_CT) {
					Map<String, Object> balanceRecordInfoMap = new HashMap<String, Object>();
					AVP_Grouped avpBalanceRecordInfo = new AVP_Grouped(avpData);
					// 查询帐期，格式YYYYMM
//					AVP Billing_Cycle = avpBalanceRecordInfo.find(5043, Constants.DIAMETER_VENDOR_CT);
//					if (Billing_Cycle != null) { 
//						 balanceRecordInfoMap.put("billingCycleId",new AVP_UTF8String(Billing_Cycle).queryValue()); 
//					}
					 
					// 余额类型标识：0通用余额、1专用余额、2其它
					AVP BalanceTypeFlag = avpBalanceRecordInfo.find(90208, Constants.DIAMETER_VENDOR_CT);
					if (BalanceTypeFlag != null) {
						balanceRecordInfoMap.put("balanceTypeFlag", String.valueOf(new AVP_Integer32(BalanceTypeFlag).queryValue()));
					}
					// 上期末余额
					AVP BalanceBegin = avpBalanceRecordInfo.find(90216, Constants.DIAMETER_VENDOR_CT);
					if (BalanceBegin != null) {
						balanceRecordInfoMap.put("balanceBegin", new AVP_Integer64(BalanceBegin).queryValue());
					}
					// 本期入帐
					AVP BalanceIn = avpBalanceRecordInfo.find(90217, Constants.DIAMETER_VENDOR_CT);
					if (BalanceIn != null) {
						balanceRecordInfoMap.put("balanceIn", new AVP_Integer64(BalanceIn).queryValue());
					}
					// 本期支出
					AVP BalanceOut = avpBalanceRecordInfo.find(90218, Constants.DIAMETER_VENDOR_CT);
					if (BalanceOut != null) {
						balanceRecordInfoMap.put("balanceOut",  new AVP_Integer64(BalanceOut).queryValue());
					}
					// 本期末余额
					AVP BalanceEnd = avpBalanceRecordInfo.find(90219, Constants.DIAMETER_VENDOR_CT);
					if (BalanceEnd != null) {
						balanceRecordInfoMap.put("balanceEnd",new AVP_Integer64(BalanceEnd).queryValue());
					}
					list.add(balanceRecordInfoMap);
				}
			}
			map.put("BalanceRecordInfo", list);
		}catch (Exception e) {
			map = null;
			_log.info("getAvpsFromMessage Exception error,msg=" + e.getMessage());
		}
		return map;
	}

	/**
	 * 由于计费侧提供的接口协议没变，只是地址调整，割接到3.0的本地网需要调用新的地址
	 * 集团电子发票API接口调整
	 * 获取判断使用的地址
	 * jf3_flag 刷新开关  配置为1则表示启用割接地市判断，配置为0则表示按现有的流程
	 * Jf3_jt_latn_id  割接地市配置项（多个地市用逗号分隔，如果配置项调整为888，则表示全部调用新地址）
	 * resultLanIdStr 区域编码
	 * cityId
	 * jf3_jt_latn_id 是84201这种
		jf3_latn_id是1001 1018 这种
		jf3_area_coee是027 0716 这种
		type 传参0 1001类 传1 84210类   返参 1 新 0 旧的
	 */
	private String getVersionType(String cityId,String type) {
		String jf3_flag = userResourceConfigService.getValue("jf3_flag","");////增加刷新开关  ,配置为1则表示启用割接地市判断，配置为0则表示按现有的流程
		String jf3_jt_latn_id = userResourceConfigService.getValue("jf3_jt_latn_id","");
		String jf3_latn_id = userResourceConfigService.getValue("jf3_latn_id","");
		String str;
		if("0".equals(type)) {
			//1001类型
			str = jf3_latn_id;
		}else {
			//84201 类型
			str = jf3_jt_latn_id;
		}
		//1 新流程  0 旧的流程
		if("1".equals(jf3_flag)) {
			if("888".equals(str)) {
				return "1";//新的
			}else {
				String[] split_jt_latn_id = str.split(",");
				for (String string : split_jt_latn_id) {
					if(string.equals(cityId)) {
						//包含,仅区分新旧
						return "1";//新的 Recharged.jf3@027.ctnbc-bon.net
					}
				}
			}
			
		}
		return "0";//旧的 SeverRecharge.SGWPAY@027.ctnbc-bon.net  
	}
}
